package controller;

import java.io.IOException;
import java.sql.*;
import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import core.*;
import model.*;

public class EditQuestion extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static PgSQL db = PgSQL.getInstance();

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		CurrentUser user = new CurrentUser(request);
		UserGroup usergroup = user.getGroup();

		int qid = Tool.intval(request.getParameter("qid"));
		if(qid > 0 && !usergroup.hasPermission(UserGroup.EDIT_QUESTION)){
			View.showMessage(request, response, "You are not permitted to edit questions.", "back");
			return;
		}else if(!usergroup.hasPermission(UserGroup.ADD_QUESTION)){
			View.showMessage(request, response, "You are not permitted to add new questions.", "back");
			return;
		}
		
		ChoiceQuestion q = null;
		if(qid > 0){
			try{
				PreparedStatement ps = db.prepareStatement("SELECT * FROM qz_choicequestion WHERE qid=?");
				ps.setInt(1, qid);
				ResultSet rs = ps.executeQuery();
				if(rs.next()){
					q = ChoiceQuestion.fromDatabase(rs);
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		if(q == null){
			q = new ChoiceQuestion();
			q.setContent("");
			q.setAnswer("");
			q.setOptions("");
			q.setQid(0);
			q.setQtid(0);
		}
		request.setAttribute("question", q);
		
		List<QuestionType> question_types = new LinkedList<QuestionType>();
		ResultSet rs = db.query("SELECT qtid,name FROM qz_questiontype");
		try{
			while(rs.next()){
				QuestionType qt = new QuestionType();
				qt.setQtid(rs.getInt(1));
				qt.setName(rs.getString(2));
				question_types.add(qt);
			}
			request.setAttribute("question_types[]", question_types.toArray());
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		View.show(request, response, "edit_choice_question");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		CurrentUser user = new CurrentUser(request);
		UserGroup usergroup = user.getGroup();
	
		String content = request.getParameter("content");
		String answer = request.getParameter("answer");
		String[] options = request.getParameterValues("options[]");
		String qtid_str = request.getParameter("qtid");
		int qid = Tool.intval(request.getParameter("qid"));
		int pid = Tool.intval(request.getParameter("pid"));
		
		if(qid > 0 && !usergroup.hasPermission(UserGroup.EDIT_QUESTION)){
			View.showMessage(request, response, "You are not permitted to edit questions.", "back");
			return;
		}else if(!usergroup.hasPermission(UserGroup.ADD_QUESTION)){
			View.showMessage(request, response, "You are not permitted to add new questions.", "back");
			return;
		}
		
		if(content == null || answer == null || options == null){
			View.showMessage(request, response, "Fill in all blanks, please.", "back");
		}
		
		if(!answer.matches("[A-Z]+")){
			View.showMessage(request, response, "Question Answer accepts no characters except capital letters.", "back");
		}
		
		content = Tool.htmlspecialchars(content);
		
		StringBuffer option_string = new StringBuffer();
		for(int i = 0; i < options.length; i++){
			option_string.append(Tool.htmlspecialchars(options[i]));
			if(i < options.length - 1){
				option_string.append('|');
			}
		}

		int qtid = 0;
		if(qtid_str != null){
			qtid = Integer.parseInt(request.getParameter("qtid"));
		}
		
		if(qid > 0){
			PreparedStatement st = db.prepareStatement("UPDATE qz_choicequestion SET content=?,answer=?, options=?, qtid=? WHERE qid=?");
			try {				
				st.setString(1, content);
				st.setString(2, answer);
				st.setString(3, new String(option_string));
				st.setInt(4, qtid);
				st.setInt(5, qid);
				
				st.executeUpdate();
				View.showMessage(request, response, "The question has been sucessfully updated!", pid <= 0 ? "QuestionList" : "EditPaper?pid=" + pid);
				
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}else{			
			PreparedStatement st = db.prepareStatement("INSERT INTO qz_choicequestion (qid, content, answer, options, qtid) VALUES (nextval('qid'), ?, ?, ?, ?)");
			try {
				st.setString(1, content);
				st.setString(2, answer);
				st.setString(3, new String(option_string));
				st.setInt(4, qtid);
				st.executeUpdate();
				
				ResultSet rs = db.query("SELECT currval('qid')");
				if(rs != null && rs.next()){
					qid = rs.getInt(1);
					if(pid > 0){
						db.update("INSERT INTO qz_papercontent (pid, qid) VALUES (" + pid + "," + qid + ")");
					}
				}
				
				View.showMessage(request, response, "The question has been successfully inserted.", pid <= 0 ? "QuestionList" : "EditPaper?pid=" + pid);
				
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
